package com.juyu.miliao.api.service;

import com.juyu.miliao.api.dao.mysql.DynamicLikeInfoDao;
import com.juyu.miliao.api.dao.redis.DynamicCommentInfoRedisDao;
import com.juyu.miliao.api.dao.redis.DynamicInfoRedisDao;
import com.juyu.miliao.api.dao.redis.FollowRedisDao;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.api.domain.dto.DynamicInfoDTO;
import com.juyu.miliao.api.domain.dto.DynamicReportInfoDTO;
import com.juyu.miliao.api.domain.vo.DynamicCommentInfoVo;
import com.juyu.miliao.api.domain.vo.DynamicDetailInfoVo;
import com.juyu.miliao.api.domain.vo.DynamicInfoVo;
import com.juyu.miliao.api.domain.vo.DynamicSourceInfoVO;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.DateUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 动态社区service
 *
 * @author xuanqicheng
 * @create 2019-21-09:47
 */
@Service
public class DynamicInfoService {


    @Autowired
    private DynamicInfoRedisDao dynamicInfoRedisDao;

    @Autowired
    private DynamicCommentInfoRedisDao dynamicCommentInfoRedisDao;

    @Autowired
    private DynamicLikeInfoDao dynamicLikeInfoDao;

    @Autowired
    private FollowRedisDao followRedisDao;

    @Autowired
    private DynamicCommentInfoService dynamicCommentInfoService;

    @Autowired
    private VestRobotMessageService vestRobotMessageService;


    @Autowired
    private UserInfoCache userInfoCache;

    @Autowired
    private AppKeyService appKeyService;
    @Transactional(rollbackFor = Exception.class)
    public void addDynamciInfo(DynamicInfoDTO dynamicInfoDTO) {

        DynamicInfo dynamicInfo = new DynamicInfo();

        BeanUtils.copyProperties(dynamicInfoDTO, dynamicInfo);

        dynamicInfoRedisDao.addDynamciInfo(dynamicInfo);

        dynamicInfoRedisDao.addDynamicSourceInfo(dynamicInfo.getDynamicId(), dynamicInfoDTO);

        String dynamicSourceUrl = "";
        if(dynamicInfo.getSourceType()==2){

            dynamicSourceUrl = dynamicInfoDTO.getVideoImgUrl();
        }else{
            dynamicSourceUrl = dynamicInfoDTO.getDynamicSourceUrls().get(0);
        }
        UserCacheVo fromUser = userInfoCache.getUserCacheInfo(dynamicInfo.getUserId());
        com.alibaba.fastjson.JSONObject ext = new com.alibaba.fastjson.JSONObject();
        ext.put("fromUserId",dynamicInfo.getUserId());
        ext.put("fromUserIcon",fromUser.getIcon());
        ext.put("commentId",0);
        ext.put("dynamicSourceUrl",dynamicSourceUrl);
//        ext.put("type",1);
        ext.put("commentReplyId",0);
        ext.put("dynamicId",-1);
        //前message:您的帖子正在审核中，请稍后在社区中刷新查看~ 修改成系统消息
        String message = "您的动态正在审核中，请耐心等待审核~";

        int stat = EnumType.TEXT_MESSAGE.state;

        vestRobotMessageService.getSendMsg(dynamicInfo.getUserId(),message);

    }

    public List<DynamicInfoVo> getDynamicInfoList(long userId, Integer page, Integer pageSize) {

        int startNum = PageUtil.getOffset(page, pageSize);

        List<DynamicInfoVo> list = dynamicInfoRedisDao.getDynamicInfoList(startNum, pageSize);

        setDynamicInfo(userId, list);

        return list;

    }

    /**
     * 设置动态列表信息
     *
     * @param list
     */
    private void setDynamicInfo(long reqUserId, List<DynamicInfoVo> list) {
        for (DynamicInfoVo obj : list) {

            boolean bl = dynamicInfoRedisDao.checkUserLikeDynamicInfoByUserId(reqUserId, obj.getDynamicId());
            if (bl) {
                obj.setIsLike(1);
            }
            int shareNumber = dynamicInfoRedisDao.getDynamicShare(obj.getDynamicId());

            String showTime = DateUtil.getShowTime(obj.getDynamicCreateTime());
            obj.setShowTime(showTime);
            //获取点赞数
            int likeNumber = dynamicInfoRedisDao.getDynamicLikeByDynamicId(obj.getDynamicId());

            int commentSize = dynamicCommentInfoRedisDao
                    .getDynamicCommentPageCountByDynamicId(obj.getDynamicId());

            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(obj.getUserId());
            obj.setNickName(userCacheVo.getNickName())
                    .setIcon(userCacheVo.getIcon())
                    .setSex(userCacheVo.getSex())
                    .setIsVip(userCacheVo.getIsVip())
                    .setVipLevel(userCacheVo.getVipLevel())
                    .setStar(userCacheVo.getStar())
                    .setMGrade(userCacheVo.getMGrade())
                    .setVGrade(userCacheVo.getVGrade())
                    .setAge(userCacheVo.getAge())
                    .setIsHost(userCacheVo.getIsHost())
                    .setCommentNumber(commentSize)
                    .setLikeNumber(likeNumber)
                    .setShareNumber(shareNumber);

            List<DynamicCommentInfo> commentInfoList = dynamicCommentInfoRedisDao
                    .getDynamicCommentPageByDynamicId(obj.getDynamicId(), 0, 2);
            if (commentInfoList.size() > 0) {

                DynamicCommentInfoVo dynamicCommentInfoVo = new DynamicCommentInfoVo();

                //获取评论信息
                DynamicCommentInfo commentInfo = commentInfoList.get(0);

                dynamicCommentInfoService.setDynamicCommentInfoVo(dynamicCommentInfoVo, commentInfo);

                List<CommentReplyInfo> commentReplyInfoList = dynamicCommentInfoRedisDao
                        .getCommentReplyInfoByCommentId(commentInfo.getId());
                if (commentReplyInfoList.size() > 0) {

                    CommentReplyInfo commentReplyInfo = commentReplyInfoList.get(0);

                    Map<String, Object> map = dynamicCommentInfoService.setCommentReplyInfo(commentReplyInfoList.size(),
                            commentReplyInfo);

                    dynamicCommentInfoVo.setReplyInfo(map);

                }
                obj.setComment(dynamicCommentInfoVo);


            } else {
                obj.setComment(new HashMap<>(1));
            }

        }
    }

    /**
     * 点赞
     *
     * @param userId
     * @param dynamicId
     * @return
     */
    public Object clickDynamicLike(Long userId, long dynamicId) {
        DynamicLikeInfo obj = new DynamicLikeInfo();
        obj.setDynamicId(dynamicId);
        obj.setUserId(userId);
        int result = dynamicLikeInfoDao.selectDynamicLike(obj);

        if (result > 0) {
            //取消点赞
            JSONObject json = new JSONObject();
            dynamicInfoRedisDao.subtractionLikeInfo(obj);
            json.put("type", "remove");
            return json;
        } else {
            //点赞
            JSONObject json = new JSONObject();
            dynamicInfoRedisDao.addLikeInfo(obj);
            json.put("type", "add");
            //发送im
            sendDynamicLikeIM(userId, dynamicId);
            return json;
        }
    }

    private void sendDynamicLikeIM(Long userId, long dynamicId) {
        DynamicDetailInfoVo dynamicDetailInfoVo=dynamicInfoRedisDao.getDynamicInfoById(dynamicId);
        if(!dynamicDetailInfoVo.getUserId().equals(userId)) {
            long fromUserId = userId;

            UserCacheVo fromUser = userInfoCache.getUserCacheInfo(fromUserId);

            String fromUserIcon = fromUser.getIcon();

            long commentId = 0;

            String dynamicSourceUrl = "";

            DynamicSourceInfoVO dynamicSourceInfoVO = dynamicDetailInfoVo.getDynamicSourceUrls().get(0);
            if (dynamicDetailInfoVo.getSourceType() == 2) {
                dynamicSourceUrl = dynamicSourceInfoVO.getVideoImgUrl();
            } else {
                dynamicSourceUrl = dynamicSourceInfoVO.getDynamicSourceUrl();
            }

            long commentReplyId = 0;

            String message = fromUser.getNickName() + "点赞你的动态：" + dynamicDetailInfoVo.getDynamicTextContent();

            com.alibaba.fastjson.JSONObject ext = new com.alibaba.fastjson.JSONObject();
            ext.put("fromUserId", fromUserId);
            ext.put("fromUserIcon", fromUserIcon);
            ext.put("commentId", commentId);
            ext.put("dynamicId", dynamicId);
            ext.put("dynamicSourceUrl", dynamicSourceUrl);
//            ext.put("type", 6);
            ext.put("commentReplyId", commentReplyId);

            int stat = EnumType.TEXT_MESSAGE.state;
            //修改成官方小助手发送  DYNAMIC_USER_ID
            vestRobotMessageService.getSendMsg(dynamicDetailInfoVo.getUserId(), EnumType.HELPER_USER_ID.state, message,
                    ext.toJSONString(), stat);
        }
    }

    /**
     * 根据动态id 查询内容
     *
     * @param dynamicId
     * @param userId    当前访问用户的id
     * @return
     */
    public Object getDynamicInfoById(long dynamicId, Long userId) {
        DynamicDetailInfoVo dynamicDetailInfoVo = dynamicInfoRedisDao.getDynamicInfoById(dynamicId);
        if (dynamicDetailInfoVo != null) {

            boolean bl = dynamicInfoRedisDao.checkUserLikeDynamicInfoByUserId(userId, dynamicId);
            if (bl) {
                dynamicDetailInfoVo.setIsLike(1);
            }

            String showTime = DateUtil.getShowTime(dynamicDetailInfoVo.getDynamicCreateTime());
            dynamicDetailInfoVo.setShowTime(showTime);

            int likeNumber = dynamicInfoRedisDao.getDynamicLikeByDynamicId(dynamicDetailInfoVo.getDynamicId());

            int shareNumber = dynamicInfoRedisDao.getDynamicShare(dynamicId);

            int commentSize = dynamicCommentInfoRedisDao
                    .getDynamicCommentPageCountByDynamicId(dynamicDetailInfoVo.getDynamicId());

            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(dynamicDetailInfoVo.getUserId());

            dynamicDetailInfoVo.setLikeNumber(likeNumber)
                    .setCommentNumber(commentSize)
                    .setNickName(userCacheVo.getNickName())
                    .setIcon(userCacheVo.getIcon())
                    .setSex(userCacheVo.getSex())
                    .setIsVip(userCacheVo.getIsVip())
                    .setVipLevel(userCacheVo.getVipLevel())
                    .setStar(userCacheVo.getStar())
                    .setMGrade(userCacheVo.getMGrade())
                    .setVGrade(userCacheVo.getVGrade())
                    .setAge(userCacheVo.getAge())
                    .setIsHost(userCacheVo.getIsHost())
                    .setShareNumber(shareNumber);

            Optional<Long> countFollow = followRedisDao.countFollow(userId, dynamicDetailInfoVo.getUserId());

            if (countFollow.isPresent() || userId.equals(dynamicDetailInfoVo.getUserId())) {

                dynamicDetailInfoVo.setIsFollow(1);
            }

            List<DynamicGiftInfo> giftInfos = dynamicInfoRedisDao.getDynamicGiftList(dynamicId);

            List<Long> giftUserList = dynamicInfoRedisDao.getDynamicGiftUserList(dynamicId);

            if (giftInfos.size() > 0) {
                Map<String, Object> giftMap = new HashMap<>(0);
                giftMap.put("giftNumber", giftInfos.size());
                List<String> iconList = new ArrayList<>();
                List<Long> list;

                if (giftUserList.size() >= 3) {
                    list = giftUserList.subList(0, 3);
                } else {

                    list = giftUserList;
                }
                for (long sendUserId : list) {
                    UserCacheVo userInfo = userInfoCache.getUserCacheInfo(sendUserId);

                    iconList.add(userInfo.getIcon());
                }
                giftMap.put("icons", iconList);

                dynamicDetailInfoVo.setGift(giftMap);
            }

            return dynamicDetailInfoVo;

        } else {
            return new HashMap<>(0);
        }

    }


    public void saveDynamicGiftInfo(GiftSpend entity,Long dynamicId) {

        long userId = Long.parseLong(entity.getOutUserId() + "");

        DynamicGiftInfo dynamicGiftInfo = new DynamicGiftInfo()
                .setDynamicId(dynamicId)
                .setSendId(entity.getSpendId())
                .setSendUserId(userId);

        dynamicInfoRedisDao.saveDynamicGiftInfo(dynamicGiftInfo);
    }

    public DynamicDetailInfoVo getDynamicInfoByDynamicId(Long dynamicId) {
        DynamicDetailInfoVo dynamicDetailInfoVo = dynamicInfoRedisDao.getDynamicInfoById(dynamicId);
        return dynamicDetailInfoVo;
    }

    /**
     * 根据用户id，查询信息
     *
     * @param reqUserId 访问用户id
     * @param userId    动态用户id
     * @param page
     * @param pageSize
     * @return
     */
    public List<DynamicInfoVo> getDynamicInfoListByUserId(long reqUserId, Long userId, Integer page, Integer pageSize) {

        int startNum = PageUtil.getOffset(page, pageSize);

        List<DynamicInfoVo> list = dynamicInfoRedisDao.getDynamicInfoListByUserId(userId, startNum, pageSize);

        setDynamicInfo(reqUserId, list);
        return list;
    }

    /**
     * 设置分享
     *
     * @param dynamicId
     */
    public void setShareInfo(Long dynamicId) {

        dynamicInfoRedisDao.setDynamicShare(dynamicId);

    }

    /**
     * 举报
     *
     * @param obj
     */
    public void setReport(DynamicReportInfoDTO obj) {
        dynamicInfoRedisDao.setReport(obj);
    }

    public List<DynamicInfoVo> getFollowDynamicInfoListByUserId(long userId, Integer page, Integer pageSize) {
        int startNum = PageUtil.getOffset(page, pageSize);

        Set<Long> set = followRedisDao.getFolllowAllByUserId(userId);

        List<Long> userIdList = new ArrayList<>(set);

        List<DynamicInfoVo> list = dynamicInfoRedisDao.getFollowDynamicInfoList(userId, userIdList, startNum, pageSize);

        setDynamicInfo(userId, list);

        return list;
    }


    public Map<String, Object> getShareDynamicInfoByDynamicId(Long dynamicId) {
        Map<String, Object> map = new HashMap<>(2);
        DynamicDetailInfoVo obj = dynamicInfoRedisDao.getDynamicInfoById(dynamicId);
        if (obj != null) {

            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(obj.getUserId());
            map.put("title", userCacheVo.getNickName());
            map.put("content", obj.getDynamicTextContent());

            List<DynamicSourceInfoVO> dynamicSourceList = obj.getDynamicSourceUrls();

            if (dynamicSourceList.size() > 0) {
                DynamicSourceInfoVO dynamicSourceInfo = dynamicSourceList.get(0);
                if (obj.getSourceType() == 1) {
                    map.put("icon", dynamicSourceInfo.getDynamicSourceUrl());
                } else if (obj.getSourceType() == 2) {
                    map.put("icon", dynamicSourceInfo.getVideoImgUrl());
                }
            }else{
                map.put("icon","");
            }

            Appkey appkey = appKeyService.getAppKeyByKey("dynamicShareUrl");
            map.put("url",appkey.getValue()+dynamicId);

        }

        return map;

    }

    public DynamicDetailInfoVo getShareTextDynamicInfoByDynamicId(Long dynamicId) {
        DynamicDetailInfoVo obj = dynamicInfoRedisDao.getDynamicInfoById(dynamicId);
        if (obj != null) {
            String showTime = DateUtil.getShowTime(obj.getDynamicCreateTime());
            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(obj.getUserId());
            obj.setNickName(userCacheVo.getNickName())
                    .setIcon(userCacheVo.getIcon())
                    .setSex(userCacheVo.getSex())
                    .setAge(userCacheVo.getAge())
                    .setIsVip(userCacheVo.getIsVip())
                    .setStar(userCacheVo.getStar())
                    .setVipLevel(userCacheVo.getVipLevel())
                    .setIsHost(userCacheVo.getIsHost())
                    .setVGrade(userCacheVo.getVGrade())
                    .setMGrade(userCacheVo.getMGrade())
                    .setShowTime(showTime);
            return obj;
        } else {
            throw new ConsumeRuntimeException("动态id不正确");
        }
    }

    public void deleteDynamicInfo(long dynamicId) {
        dynamicInfoRedisDao.deleteDyanmicInfo(dynamicId);
    }
}
